<?php

namespace app\modules\Merchant\service;

use app\modules\Merchant\models\categoryModel;

class Category
{
    public static function getCategoryIds($id, $dianpu_id)
    {
        $categoryIds = self::recursionGetCategoryIds($id, $dianpu_id);
        return $categoryIds;
    }

    public static function recursionGetCategoryIds($id, $dianpu_id)
    {
        if(empty($dianpu_id)){
            return null;
        }
        $ids = [];
        $category_ids = categoryModel::query()->where('dianpu_id', $dianpu_id)->where('pid', $id)->pluck('id');
        if ($category_ids) {
            foreach ($category_ids as $k => $v) {
                $childrenCategoryIds = self::recursionGetCategoryIds($v, $dianpu_id);
                if ($childrenCategoryIds && count($childrenCategoryIds) > 0) $ids = array_merge($ids, $childrenCategoryIds);
            }
        }
        return array_merge($ids, [intval($id)]);
    }

    public static function getCategoryDetail($id, $dianpu_id)
    {
        if(empty($dianpu_id) || empty($id)){
            return null;
        }
        return categoryModel::query()->where('dianpu_id', $dianpu_id)->where(['id' => $id, 'pid' => 0, 'status' => 1])->first();
    }

    public static function getCategoryList($id, $dianpu_id)
    {
        if(empty($dianpu_id)){
            return null;
        }
        $category = categoryModel::query()->where('dianpu_id', $dianpu_id)->where(['status' => 1])->get()->toArray();
        $tree_data = get_tree($category);
        foreach ($tree_data as $branch) {
            if ($id == $branch['id']) {
                return $branch;
            }
        }
        return $tree_data;
    }

    #[递归获取商品目录树]
    public static function categoryTree($dianpu_id)
    {
        if(empty($dianpu_id)){
            return null;
        }
        $children = categoryModel::query()->where('dianpu_id', $dianpu_id)->where('pid', 0)->select('id', 'name as text')->orderBy('weigh', 'DESC')->orderBy('id', 'ASC')->get();
        if ($children->isNotEmpty()) {
            foreach ($children as $v) {
                $v->name = htmlentities($v->name);
                self::subCategoryTree($v, $dianpu_id);
            }
        }
        return $children;
    }

    private static function subCategoryTree(&$item, $dianpu_id)
    {
        if(empty($dianpu_id)){
            return null;
        }
        $children = categoryModel::query()->where('dianpu_id', $dianpu_id)->where('pid', $item->id)->select('id', 'name as text')->orderBy('weigh', 'DESC')->orderBy('id', 'ASC')->get();
        if ($children->isNotEmpty()) {
            $item && $item->children = $children;
            foreach ($children as $v) {
                $v->name = htmlentities($v->name);
                self::subCategoryTree($v, $dianpu_id);
            }
        }
        return $children;
    }
}